package com.th.apicenter.jd.service;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;

import java.time.Instant;
import java.util.*;

@Service
public class JdService {

    private final String APP_KEY = "6i7qk77le0vq4dvg";
    private final String APP_SECRET = "a94i039wxo2d0xs9dq6hgz71lznpl7gd";

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    //公共参数集合

    /**
     * 京东订单查询（优化版）
     */
    public String queryJDOrders(String startTime,String endTime) {
        // 1. 构建基础参数
        // 1. 构建基础参数（包括timestamp）
        Map<String, String> params = new LinkedHashMap<>();
        params.put("appkey", APP_KEY);
        params.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("type", "1");
        params.put("pids", "1002044596_4100562302_3101923217");
        params.put("pageIndex", "1");
        params.put("pageSize", "10");

        // 2. 生成签名（传入appSecret）
        String sign = generateSign(params, APP_SECRET);
        params.put("sign", sign);
        String s = JSON.toJSONString(params);
        // 3. 设置请求头
        HttpRequest request = HttpUtil.createPost("https://gylmsturl.gylm2020.com/gylmJ/api/v1/bcjd/orderList"); // 替换为真实URL
        request.header("Content-Type", "application/json;charset=UTF-8");
        request.header("Accept", "application/json");
        request.body(JSON.toJSONString(params));
        //发送请求
        String body = request.execute().body();
        return body;
    }

    /**
     * 生成请求签名（线程安全版）
     */
    public static String generateSign(Map<String, ?> params,String appSecret) {
        // 1. 参数排序
        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);

        // 2. 拼接参数字符串
        StringBuilder query = new StringBuilder(appSecret);
        for (String key : keys) {
            query.append(key).append(params.get(key));
        }
        query.append(appSecret);
        String s = query.toString();
        // 3. MD5加密（优化异常处理）
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(s.getBytes(StandardCharsets.UTF_8));

            // 3. 转换为十六进制大写字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : digest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString().toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 algorithm not available", e);
        }
    }

}
